package com.pur.zsms.pmsnmanage.role.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.pur.zsms.common.dao.GenericDao;
import com.pur.zsms.common.dao.JpaTemplate;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.documentsmanage.po.DomPo;
import com.pur.zsms.ordercustommanage.po.OrderCustPo;
import com.pur.zsms.pmsnmanage.menu.po.MenuPo;
import com.pur.zsms.pmsnmanage.role.dao.IRoleDao;
import com.pur.zsms.pmsnmanage.role.po.RoleMenuPo;
import com.pur.zsms.pmsnmanage.role.po.RolePo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.po.UserRolePo;

/**
 * 角色Dao实现类
 * 
 * @author xin
 * 
 */
@Repository("roleDao")
public class RoleDaoImpl extends GenericDao implements IRoleDao {

	public PaginationSupport listRole(PageController pageController, RoleVo roleVo) throws GenericException {
		StringBuffer ql = new StringBuffer();
		ql.append("select * from t_role r where 1 =1 ");
		if (roleVo != null) {
			if (StringUtils.isNotBlank(roleVo.getRoleName())) {
				ql.append(" and r.role_name like '%" + roleVo.getRoleName().trim() + "%' ");
			}
			if (StringUtils.isNotBlank(roleVo.getIsActive())) {
				ql.append(" and r.is_active = '" + roleVo.getIsActive().trim() + "' ");
			}
		}
		ql.append(" order by r.role_id desc");
		return this.findByNativeQuery(ql.toString(), RolePo.class, pageController);
	}

	public List<RolePo> listAllRole() throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o from RolePo o where o.isActive <> 'N'");
		List<RolePo> list = template.find(ql.toString(), null);
		return list;
	}

	public List<RolePo> listRoleByIdentity(String identity) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o from RolePo o where o.isActive <> 'N' AND identity='" + identity + "'");
		List<RolePo> list = template.find(ql.toString(), null);
		return list;
	}

	public List<RolePo> findByRoleName(String roleName) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from RolePo o where o.roleName=" + roleName);
		List<RolePo> list = template.find(ql.toString(), null);
		return list;
	}

	public List<RolePo> getRolePoByRoleNameUserId(UserPo userPo, String roleName) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" SELECT r FROM RolePo r WHERE EXISTS (SELECT 1 FROM UserRolePo rm WHERE rm.userId = '" + userPo.getUserId()
				+ "' AND rm.roleId=r.roleId AND r.roleName= '" + roleName + "') ");
		List<RolePo> list = template.find(ql.toString(), null);
		return list;
	}

	public void addRole(RolePo c) throws GenericException {
		this.persist(c);

	}

	public void updateRole(RolePo c) throws GenericException {
		this.merge(c);
	}

	public void deleteRole(Long roleId) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" delete RolePo o where o.roleId=" + roleId);
		template.executeUpdate(ql.toString());
	}

	public List<UserRolePo> listUserRoleByRoleId(String roleId) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from UserRolePo o where o.roleId=" + roleId);
		List<UserRolePo> list = template.find(ql.toString(), null);
		return list;
	}

	@Override
	public void addRoleMenu(RoleVo roleVo, Long[] menuIds) throws GenericException {
		RolePo rolePo = new RolePo();
		rolePo.setInsertBy(roleVo.getInsertBy());
		rolePo.setIsActive(roleVo.getIsActive());
		rolePo.setRoleName(roleVo.getRoleName());
		this.entityManager.persist(rolePo);

		for (int i = 0; i < menuIds.length; i++) {
			RoleMenuPo roleMenuPo = new RoleMenuPo();
			roleMenuPo.setRoleId(rolePo.getRoleId());
			roleMenuPo.setMenuId(menuIds[i]);
			roleMenuPo.setInsertBy(roleVo.getInsertBy());
			roleMenuPo.setUpdateBy(roleVo.getInsertBy());
			this.entityManager.persist(roleMenuPo);

		}
	}

	public void addRoleMenu(RoleVo roleVo) throws GenericException {
		RolePo rolePo = new RolePo();
		rolePo.setInsertBy(roleVo.getInsertBy());
		rolePo.setIsActive(roleVo.getIsActive());
		rolePo.setRoleName(roleVo.getRoleName());
		rolePo.setIdentity(roleVo.getIdentity());
		this.entityManager.persist(rolePo);

		String[] menuIdAll = roleVo.getMenuIdAll().split(",");
		for (String menuId : menuIdAll) {

			// 校验 是否已经存在
			if (!checkExistRoleMenuPo(menuId, rolePo.getRoleId())) {
				continue;
			}

			RoleMenuPo roleMenuPo = new RoleMenuPo();
			roleMenuPo.setRoleId(rolePo.getRoleId());
			roleMenuPo.setMenuId(Long.valueOf(menuId));
			roleMenuPo.setInsertBy(roleVo.getInsertBy());
			roleMenuPo.setUpdateBy(roleVo.getInsertBy());
			this.entityManager.persist(roleMenuPo);

			// 父页面插入

			insertParentMenuRole(menuId, rolePo, roleVo);

			// 子页面插入
			insertSunMenuRole(menuId, rolePo, roleVo);

		}
	}

	@Override
	public RolePo findRoleById(Long roleId) throws GenericException {
		return this.entityManager.find(RolePo.class, roleId);
	}

	public RolePo findRoleByCompanyIdForSupplier(int companyId) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from RolePo o where o.userId=" + companyId);
		List<RolePo> list = template.find(ql.toString(), null);
		return list.get(0);
	}

	public UserPo findUserById(String userId) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from UserPo o where o.userId=" + userId);
		List<UserPo> list = template.find(ql.toString(), null);
		return list.get(0);
	}

	@Override
	public List<RoleMenuPo> findMenusByRole(Long roleId) throws GenericException {
		Query query = this.entityManager.createQuery("From RoleMenuPo r where r.roleId=:roleId");
		query.setParameter("roleId", roleId);
		return query.getResultList();
	}

	@Override
	public List<RoleMenuPo> findRoleMenus(Long roleId) throws GenericException {
		Query query = this.entityManager.createQuery("From RoleMenuPo r where r.roleId=:roleId");
		query.setParameter("roleId", roleId);
		return query.getResultList();
	}

	@Override
	public void deleteRoleMenu(RoleMenuPo roleMenuPo) throws GenericException {

		this.entityManager.remove(roleMenuPo);
	}

	@Override
	public void updateRoleMenu(RoleVo roleVo) throws GenericException {
		RolePo rolePo = new RolePo();
		rolePo.setRoleId(roleVo.getRoleId());
		rolePo.setInsertBy(roleVo.getInsertBy());
		rolePo.setIsActive(roleVo.getIsActive());
		rolePo.setRoleName(roleVo.getRoleName());
		rolePo.setUpdateBy(roleVo.getUpdateBy());
		rolePo.setUpdateTime(roleVo.getUpdateTime());

		this.entityManager.merge(rolePo);
		// 删除已有关系表
		List<RoleMenuPo> roleMenuPolist = findRoleMenus(rolePo.getRoleId());
		if (roleMenuPolist != null && roleMenuPolist.size() > 0) {
			for (RoleMenuPo roleMenuPo : roleMenuPolist) {
				deleteRoleMenu(roleMenuPo);
			}
		}

		String[] menuIdAll = roleVo.getMenuIdAll().split(",");
		for (String menuId : menuIdAll) {

			// 校验 是否已经存在
			if (!checkExistRoleMenuPo(menuId, rolePo.getRoleId())) {
				continue;
			}

			RoleMenuPo roleMenuPo = new RoleMenuPo();
			roleMenuPo.setRoleId(rolePo.getRoleId());
			roleMenuPo.setMenuId(Long.valueOf(menuId));
			roleMenuPo.setInsertBy(roleVo.getInsertBy());
			roleMenuPo.setUpdateBy(roleVo.getInsertBy());
			this.entityManager.persist(roleMenuPo);

			// 父页面插入

			insertParentMenuRole(menuId, rolePo, roleVo);

			// 子页面插入
			insertSunMenuRole(menuId, rolePo, roleVo);

		}
	}

	@Override
	public void addRoleMenu(RoleMenuPo roleMenuPo) throws GenericException {
		this.entityManager.persist(roleMenuPo);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserRolePo> findUserRoles(Long roleId) throws GenericException {
		return this.entityManager.createQuery("From UserRolePo ur where ur.roleId=:roleId").setParameter("roleId", roleId).getResultList();
	}

	/*
	 * @Override public void updateRoleMenu(RoleVo roleVo, Long[] menuIds)
	 * throws GenericException { RolePo rolePo =
	 * this.entityManager.find(RolePo.class, roleVo.getRoleId());
	 * rolePo.setRoleName(roleVo.getRoleName());
	 * rolePo.setIsActive(roleVo.getIsActive());
	 * rolePo.setUpdateBy(roleVo.getUpdateBy()); rolePo.setUpdateTime(new
	 * Date()); this.entityManager.merge(rolePo);
	 * 
	 * // 角色菜单集合 List<RoleMenuPo> roleMenus =
	 * this.entityManager.createQuery("From RoleMenuPo r where r.roleId=:roleId"
	 * ) .setParameter("roleId", roleVo.getRoleId()).getResultList(); //要删除的集合
	 * List<RoleMenuPo> deleteRoleMenus = new ArrayList<RoleMenuPo>();
	 * 
	 * //要修改的集合 List<RoleMenuPo> updateRoleMenus = new ArrayList<RoleMenuPo>();
	 * 
	 * 
	 * for (int i = 0; i < menuIds.length; i++) { Query query =
	 * this.entityManager
	 * .createQuery("From RoleMenuPo r where r.roleId=:roleId and r.menuId=:menuId"
	 * ); query.setParameter("roleId", roleVo.getRoleId());
	 * query.setParameter("menuId", menuIds[i]); RoleMenuPo roleMenuPo =
	 * (RoleMenuPo) query.getSingleResult();
	 * roleMenuPo.setRoleId(rolePo.getRoleId());
	 * roleMenuPo.setMenuId(menuIds[i]);
	 * roleMenuPo.setUpdateBy(roleVo.getUpdateBy());
	 * this.entityManager.merge(roleMenuPo);
	 * 
	 * } }
	 */
	public List<MenuPo> getAllMenuPo(long id) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from MenuPo o  where o.parentMenuId='" + id + "'");
		List<MenuPo> list = template.find(ql.toString(), null);
		return list;
	}

	@Override
	public List<MenuPo> getParentMenuById(String menuId) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from MenuPo o where  EXISTS (SELECT 1 FROM  MenuPo me WHERE  me.menuId = " + menuId + " AND me.parentMenuId =o.menuId) ");
		List<MenuPo> list = template.find(ql.toString(), null);
		return list;
	}

	public List<MenuPo> getSunMenuById(String menuId) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from MenuPo o where  EXISTS (SELECT 1 FROM  MenuPo me WHERE  me.menuId = o.menuId AND me.parentMenuId ='" + menuId + "') ");
		List<MenuPo> list = template.find(ql.toString(), null);
		return list;
	}

	public List<RoleMenuPo> existRoleMenuPo(String menuId, long roleId) throws GenericException {
		JpaTemplate template = this.getTemplate();
		StringBuffer ql = new StringBuffer();
		ql.append(" select o ");
		ql.append(" from RoleMenuPo o where o.roleId= '" + roleId + "'AND o.menuId = '" + menuId + "' ");
		List<RoleMenuPo> list = template.find(ql.toString(), null);
		return list;
	}

	public boolean checkExistRoleMenuPo(String menuId, long roleId) throws GenericException {
		List<RoleMenuPo> roleMenuPolist = existRoleMenuPo(menuId, roleId);
		if (roleMenuPolist != null && roleMenuPolist.size() > 0) {
			return false;
		}
		return true;
	}

	// 父页面插入方法
	public void insertParentMenuRole(String menuId, RolePo rolePo, RoleVo roleVo) throws GenericException {
		List<MenuPo> menuPoListParent = getParentMenuById(menuId);
		if (menuPoListParent != null && menuPoListParent.size() > 0) {

			// 校验 是否已经存在
			if (checkExistRoleMenuPo(String.valueOf(menuPoListParent.get(0).getMenuId()), rolePo.getRoleId())) {
				RoleMenuPo roleMenuPoParent = new RoleMenuPo();
				roleMenuPoParent.setRoleId(rolePo.getRoleId());
				roleMenuPoParent.setMenuId(menuPoListParent.get(0).getMenuId());
				roleMenuPoParent.setInsertBy(roleVo.getInsertBy());
				roleMenuPoParent.setUpdateBy(roleVo.getInsertBy());
				this.entityManager.persist(roleMenuPoParent);

				insertParentMenuRole(String.valueOf(menuPoListParent.get(0).getMenuId()), rolePo, roleVo);
			}

		}
	}

	// 子页面插入方法
	public void insertSunMenuRole(String menuId, RolePo rolePo, RoleVo roleVo) throws GenericException {
		List<MenuPo> menuPoListSun = getSunMenuById(menuId);
		if (menuPoListSun != null && menuPoListSun.size() > 0) {
			for (MenuPo menuPo : menuPoListSun) {
				// 校验 是否已经存在
				if (checkExistRoleMenuPo(String.valueOf(menuPo.getMenuId()), rolePo.getRoleId())) {
					RoleMenuPo roleMenuPoParent = new RoleMenuPo();
					roleMenuPoParent.setRoleId(rolePo.getRoleId());
					roleMenuPoParent.setMenuId(menuPo.getMenuId());
					roleMenuPoParent.setInsertBy(roleVo.getInsertBy());
					roleMenuPoParent.setUpdateBy(roleVo.getInsertBy());
					this.entityManager.persist(roleMenuPoParent);

					insertSunMenuRole(String.valueOf(menuPo.getMenuId()), rolePo, roleVo);
				}
			}
		}
	}

}
